﻿using CorrectTowerHeightTool.Model;
using DetectSys;
using DetectSys.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CorrectTowerHeightTool.Bll
{
    public class PhotoCorrectBll
    {
        public PhotoCorrect[] Parse(String dir) 
        {
            List<PhotoCorrect> photoCorrects = new List<PhotoCorrect>();
            string[] extenArr = new string[] { ".jpg",".jpeg" };
            string[] files = System.IO.Directory.GetFiles(dir);
            string[] imgs = files.Where(i => extenArr.Contains(Path.GetExtension(i).ToLower())).ToArray();
            if (imgs == null || imgs.Length < 1)
            {
                Console.WriteLine($"目录{dir}下 图像不存在");               
                return photoCorrects.ToArray();
            }

            foreach (var img in imgs)
            {
                Exif exif = new Exif(img);
                PhotoCorrect photoCorrect = new PhotoCorrect();
                photoCorrect.ImageUrl = img;
                photoCorrect.ImageName = Path.GetFileName(img);
                photoCorrect.HeightOld = exif.GPSAlt;
                photoCorrects.Add(photoCorrect);
            }

            return photoCorrects.ToArray();
        }

        internal double ParseHeight(string towerPath, string img)
        {
            string url = Path.Combine(towerPath,img);
            if (!File.Exists(url))
            {
                throw new FileNotFoundException(url);
            }
            Exif exif = new Exif(url);
            return exif.GPSAlt;
        }

        internal void ActCorrect(Dictionary<string, List<PhotoCorrect>> dic)
        {           
            List<PhotoCorrect> photos = new List<PhotoCorrect>();
            foreach (var kv in dic)
            {
                photos.AddRange(kv.Value);
            }

            int allCount = photos.Count;
            int index = 1;
            foreach (var kv in dic)
            {               
                string towerNo = kv.Key;               
                var ps = kv.Value;
                foreach (var p in ps)
                {
                    ExifWriter exifWriter = new ExifWriter();                    
                    exifWriter.PRV_Operate(p.ImageUrl,p.HeightNew,p.ImageUrl);
                    string msg = $"{index}/{allCount} {towerNo} {p.ImageName} {p.HeightOld} -> {p.HeightNew} {p.CorrectOffset}";
                    Console.WriteLine(msg);
                    C.LogtoText("","",msg);
                    index++;
                }
            }
        }
    }
}
